package com.ly.demo.controller;

import cn.hutool.http.server.HttpServerRequest;
import cn.hutool.json.JSONUtil;
import com.ly.demo.entity.SmResult;
import com.ly.demo.entity.UserEntity;
import com.ly.demo.entity.VoiceToTextReqReq;
import com.ly.demo.utils.CommonUtil;
import com.ly.demo.vo.MailDTO;
import lombok.extern.slf4j.Slf4j;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Response;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.UnsupportedAudioFileException;
import java.io.*;
import java.util.Base64;

/**
 * @Author liuyang
 * @Date 2023/6/21 14:11
 **/
@Slf4j
@RestController
@RequestMapping("/test")
public class TestController {

    @GetMapping("/isSec")
    public void isSec(HttpServletRequest request) {
        System.out.println(request.isSecure());
    }


    @PostMapping("/sendMail")
    public void sendMail(@RequestBody MailDTO mailDTO) {
        CommonUtil.sendMail(mailDTO.getTos(), mailDTO.getSubject(), mailDTO.getContent());
    }


    @PostMapping("/getAudioDurationInSeconds")
    public SmResult getAudioDurationInSeconds(@RequestBody VoiceToTextReqReq audioFile) {
        audioFile.getAudioDurationInSeconds();
        return SmResult.ok();
    }

    public static void main(String[] args) {
        UserEntity userEntity = new UserEntity();
        userEntity.setName("ddd");
        String nonce = JSONUtil.toJsonStr(userEntity);
        okhttp3.RequestBody requestBody = okhttp3.RequestBody.create(MediaType.parse("application/json"), nonce);
        try {
            okhttp3.Request request = new okhttp3.Request.Builder().url("http://localhost:8088/test/testPostman")
                    .addHeader("Content-Type", "application/json")
                    .method("POST", requestBody).build();
            OkHttpClient client = new OkHttpClient();
            Response response = client.newCall(request).execute();
            if (!response.isSuccessful()) {
                System.out.println(response.body().string());
                return;
            }
            String rspBody = response.body().string();
            System.out.println(rspBody);
            return ;
        } catch (Exception e) {
            log.error("[getSmnToken] error e", e);
            throw new RuntimeException(e);
        }
    }
    @PostMapping("/getFileInSeconds")
    public SmResult getFileInSeconds(@RequestPart MultipartFile multipartFile) throws IOException, UnsupportedAudioFileException {
        File file = new File(multipartFile.getOriginalFilename());
        try (FileOutputStream fos = new FileOutputStream(file)) {
            fos.write(multipartFile.getBytes());
        }
        String base64Audio = convertFileToBase64(file);
        writeBase64ToFile(base64Audio, "base64.text");

        AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(file);
        AudioFormat format = audioInputStream.getFormat();
        long audioFileLength = file.length();
        int frameSize = format.getFrameSize();
        float frameRate = format.getFrameRate();
        float durationInSeconds = (audioFileLength / (frameSize * frameRate));
        return SmResult.ok(durationInSeconds);
    }

    // 将文件内容转换为Base64字符串
    private String convertFileToBase64(File file) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buffer = new byte[8192];
        int bytesRead;
        try (FileInputStream fis = new FileInputStream(file)) {
            while ((bytesRead = fis.read(buffer)) != -1) {
                baos.write(buffer, 0, bytesRead);
            }
        }
        byte[] bytes = baos.toByteArray();
        return Base64.getEncoder().encodeToString(bytes);
    }

    private void writeBase64ToFile(String base64String, String filePath) throws IOException {
        try (FileOutputStream fos = new FileOutputStream(filePath)) {
            fos.write(base64String.getBytes());
        }
    }

}
